<template>
  <div>
    <h2>添加待办事项</h2>
    <form @submit.prevent="addTodo">
      <div class="form-group">
        <label for="title">标题:</label>
        <input type="text" class="form-control" id="title" v-model="newTodo.Title" required>
      </div>
      <div class="form-group">
        <label for="remindertime">提醒日期:</label>
        <input type="date" class="form-control" id="remindertime" v-model="newTodo.remindertime" min="{{ tomorrowDate }}" required>
      </div>
      <div class="form-group">
        <label for="level">等级:</label>
        <input type="number" class="form-control" id="level" v-model="newTodo.level" required>
      </div>
      <button type="submit" class="btn btn-primary" :disabled="isLoading">
        <span v-if="isLoading">提交中...</span>
        <span v-else>添加待办事项</span>
      </button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);

    return {
      newTodo: {
        Title: '',
        remindertime: tomorrow.toISOString().substr(0, 10),
        isdone: 0,
        level: 0, // 添加 level 字段
      },
      tomorrowDate: new Date(tomorrow).toISOString().substr(0, 10),
      isLoading: false,
    };
  },
  methods: {
    addTodo() {
      this.isLoading = true;

      const apiUrl = 'http://1.15.7.2/api/v1/db/data/v1/pud92sjzrgeval5/ToDoNextday';
      const headers = {
        'accept': 'application/json',
        'xc-auth': 'CBAkCNzQNnqYYUC1anRQjNVb38CNPTEnORZDv8yO',
        'xc-token': 'CBAkCNzQNnqYYUC1anRQjNVb38CNPTEnORZDv8yO',
        'Content-Type': 'application/json',
      };

      // 发送 POST 请求
      fetch(apiUrl, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(this.newTodo),
      })
        .then(response => response.json())
        .then(data => {
          console.log('添加成功:', data);
          this.isLoading = false;
          // 清空表单
          this.newTodo.Title = '';
          this.newTodo.remindertime = '';
          this.newTodo.isdone = 0;
          this.newTodo.level = 0; // 重置 level 字段
          // 重新加载整个页面
          window.location.reload();
        })
        .catch(error => {
          console.error('添加失败:', error);
          this.isLoading = false;
        });
    },
  },
};
</script>
